import TagGroup from '@/components/TagGroup';
import { mediaOrganization, updateInterview } from '@/services/api/api-needs';
import { CheckCircleTwoTone, EditOutlined, SendOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProForm,
  ProFormCascader,
  ProFormDateRangePicker,
  ProFormInstance,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Cascader, message } from 'antd';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';

interface EditNeedsProps {
  data: NeedsData.NeedsDetails;
  onRefurbish: () => void;
}

const EditNeeds: React.FC<EditNeedsProps> = ({ data, onRefurbish }) => {
  const access = useAccess();
  const { initialState, setInitialState } = useModel('@@initialState');

  const formRef = useRef<ProFormInstance>();

  const [openAddActive, setOpenAddActive] = useState<boolean>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  /**
   * 推送单位数据
   */
  const [treeMediaOrganizationData, setTreeMediaOrganizationDataState] = useState<DataNode[]>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 媒体
   */
  const loadInitMediaOrganization = async () => {
    try {
      const response = await mediaOrganization();
      if (response.code === 0) {
        setTreeMediaOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };
  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <DrawerForm
      key="drawer_form_edit_needs_release"
      title="编辑"
      drawerProps={{
        destroyOnClose: true,
        width: 690,
        maskClosable: false,
      }}
      formRef={formRef}
      trigger={
        <Button
          key="button_edit_needs_release"
          icon={<EditOutlined />}
          type="primary"
          style={{
            background: '#FA8C16',
          }}
        >
          编辑
        </Button>
      }
      initialValues={{
        initiateOrganization: data.initiateOrganization,
        name: data.name,
        interviewees: data.interviewees,
        interviewTimes: data.interviewTimes,
        assignOrganizationIds: data.assignOrganizationCascaderIds,
        location: data.location,
      }}
      open={openAddActive}
      onOpenChange={(visible) => {
        setOpenAddActive(visible);
        if (visible) {
          loadInitMediaOrganization();
        } else {
        }
      }}
      layout="horizontal"
      submitter={{
        render: (props, defaultDoms) => {
          return [
            <Button onClick={() => setOpenAddActive(false)}>取消</Button>,
            <Button
              key="button_add_interview"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                /**
                 * ======================
                 * 直接发布
                 * ======================
                 */
                const values = formRef.current?.getFieldsValue();

                if (!values.name) {
                  message.warning('请输入采访主题');
                  return;
                }

                if (!(values.assignOrganizationIds && values.assignOrganizationIds.length > 0)) {
                  message.warning('请选择至少一个采访媒体');
                  return;
                }

                if (!(values.interviewTimes && values.interviewTimes.length > 0)) {
                  message.warning('请选择采访时间');
                  return;
                }

                if (!values.location) {
                  message.warning('请输入采访地点');
                  return;
                }

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_add_interview'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                const values = formRef.current?.getFieldsValue();

                values.interviewTimes = values.interviewTimes.map((item: any) =>
                  dayjs(item).format('YYYY-MM-DD HH:mm:ss'),
                );

                const response = await updateInterview({
                  ...values,
                  id: data.id,
                  createdSource: 1,
                });

                if (response.code === 0) {
                  message.success('提交成功');
                  setOpenAddActive(false);
                  onRefurbish();
                  return true;
                } else {
                  return false;
                }
              }}
            />,
          ];
        },
      }}
    >
      <ProFormText
        width="xl"
        name="name"
        label="采访主题"
        required={true}
        fieldProps={{
          allowClear: true,
          maxLength: 200,
        }}
      />
      <ProForm.Item
        label={
          <span
            style={{
              marginLeft: '11px',
            }}
          >
            采访对象
          </span>
        }
        name="interviewees"
        extra="为保证后续审核，请尽量填写被采访对象"
      >
        <TagGroup addText={'点击新增'} />
      </ProForm.Item>

      <ProFormCascader
        width="xl"
        label="采访媒体"
        name="assignOrganizationIds"
        placeholder="选择媒体"
        required={true}
        fieldProps={{
          options: treeMediaOrganizationData,
          showSearch: { filter },
          multiple: true,
          removeIcon: true,
          allowClear: true,
          maxTagCount: 'responsive',
          showCheckedStrategy: Cascader.SHOW_CHILD,
        }}
        extra="请根据实际需求选择媒体单位"
      />

      <ProFormDateRangePicker
        name="interviewTimes"
        label="采访时间"
        allowClear
        required={true}
        width="xl"
        fieldProps={{
          allowClear: true,
          format: 'YYYY-MM-DD',
          disabledDate: (current) => {
            return current && current < dayjs().endOf('day');
          },
        }}
        extra="需求方期望的采访开始时间与结束时间"
      />

      <ProFormTextArea
        width="xl"
        name="location"
        label="采访地点"
        required={true}
        fieldProps={{
          allowClear: true,
          maxLength: 200,
        }}
      />
    </DrawerForm>
  );
};
export default EditNeeds;
